package com.da.javatest.niuke.baodian;

/**
 * @author chenlida
 * @date 2020/10/9 10:33
 * https://www.nowcoder.com/practice/ed7d014b42e740679c4bd69b9d9c49b9?tpId=8&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C30Exchange {
    public static int exchangeOddEven(int x) {
        String s = Integer.toBinaryString(x);
        if ((s.length() & 1) == 1) {
            s = "0" + s;
        }
        char[] chars = s.toCharArray();
        for (int length = chars.length - 1; length >= 0; length -= 2) {
            char temp = chars[length];
            chars[length] = chars[length - 1];
            chars[length - 1] = temp;
        }
        return Integer.valueOf(new String(chars), 2);
    }

    public static void main(String[] args) {
        System.out.println(exchangeOddEven(5));
        System.out.println(exchangeOddEven(10));
    }

    public int exchangeOddEven2(int x) {
        int odd = x & (0x55555555);
        int even = x & (0xaaaaaaaa);
        return (odd << 1) + (even >>> 1);// 无符号右移，高位补0
    }
}
